package com.atguigui.leetcode1;

/**
 * 2765. 最长交替子序列
 * Project: leetcode
 * Package: com.atguigui.leetcode1
 * Version: 1.0
 * <p>
 * Created by WJX on 2023/7/10 13:06
 */
public class P2765LongestAlternatingSubarray {
    public static void main(String[] args) {
        Solution solution = new P2765LongestAlternatingSubarray().new Solution();

        int[] arr = {3, 2, 3, 3, 2, 5, 2, 5, 4};

        System.out.println(solution.alternatingSubarray(arr));

    }

    class Solution {
        public int alternatingSubarray(int[] nums) {
            int n = nums.length;
            int ans = -1;
            int length = -1;


            for (int i = 1; i < n; i++) {
                if (length > 0 && nums[i] == nums[i - 2]) {
                    length++;
                } else if (nums[i] - nums[i - 1] == 1) {
                    length = 2;
                } else {
                    length = -1;
                }
                ans = Math.max(ans, length);
            }

            return ans;
        }
    }
}
